const express = require('express')
var crypto = require('crypto');
const fs = require('fs')
var superagent = require('superagent');
const { response } = require('express');
const router = express.Router()
const app = express()

var readFile = function (fileName){
    return new Promise(function (resolve, reject){
      fs.readFile(fileName, function(error, data){
        if (error) return reject(error);
        resolve(data);
      });
    });
  };

router.get('/login', (req, res) => {
  res.header("Access-Control-Allow-Origin","*")
  res.header("Access-Control-Allow-Headers","content-type")
  res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS")
    let plateData = {}
    plateData.plate = req.query
    fs.readFile('./files/token.txt','utf8',function(err, data){
        plateData.token = data
        fs.readFile('./files/xPermId.txt','utf8',function(err, data){
            plateData.xPermId = data
            getData(plateData)
            .then((response)=> {
              console.log('router getData then',response, response.code ==200)
                if(response.code !=200){
                  let dst =   loginGetData(plateData.plate).then((result)=>{
                    console.log('dst',result)
                    res.send(result)
                  })
                }else if(!response.phone && response.code==200){
                  console.log('查不到占位')
                  res.send({'code': 500, "message": '查不到占位车牌'})
                }
                else{
                    getPhone(response).then((responseData)=> {
                       res.send(responseData.text)
                    },(err) => {
                      res.send(err)
                    })
                }
                return false
            })
        })
    })
})

let getData = (ReqData, plate)=>{
    var get_url = 'https://mecs.fleetingpower.com/services/v3/gaiaMobile/car/query';
    var palteData = ReqData.plate ? ReqData.plate : plate
    console.log('palteData', palteData)
    var time = new Date().getTime()
    return new Promise((resolve,reject)=>{
    var sign = signGenerate(palteData)
    console.log('sign',sign, ReqData)
    superagent.post(get_url)
    // .set("Cookie", ReqData.cookie)
    .set('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
    .set('origin','https://mp-merchant.fleetingpower.com')
    .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36')
    .set('x-app-key','broker_portal')
    .set('sign',sign)
    .set('authority','mecs.fleetingpower.com')
    .set('path','/services/v3/gaiaMobile/car/query')
    .set('scheme','https')
    .set('timestamp',time)
    .set('x-perm-id',ReqData.xPermId)
    .set('x-broker-token',ReqData.token)
    .set('referer', 'https://mp-merchant.fleetingpower.com/')
    .send(palteData)
    .end((err,response)=>{
      var data = JSON.parse(response.text)
      console.log('getData response.text',response.text)
      if(data.code!=200 || !data.result){
        // return data
        console.log('reject',response.headers['x-perm-id'])
        // reject(err)
        // res.send(data)
        // res.send('ss')
        resolve(data)
      }else{
        var res= {}
        
        res = {...data.result[0], xPermId: response.headers['x-perm-id'], token: ReqData.token}
        console.log('getData response',res)
        resolve(res);
      }
      
    })
    })
}


var phone_url = 'https://mecs.fleetingpower.com/services/v3/gaiaMobile/car/getPrivateNumber'

let getPhone = (ReqData)=>{//抓页面
  var phoneData = {encryptPhone: ReqData.encryptPhone}
  var time = new Date().getTime()
  console.log('getPhone ReqData', ReqData)
return new Promise((resolve,reject)=>{
  var sign = signGenerate(phoneData)
superagent.post(phone_url)
.set('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
.set('origin','https://mp-merchant.fleetingpower.com')
.set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36')
.set('x-app-key','broker_portal')
.set('sign',sign)
.set('authority','mecs.fleetingpower.com')
.set('path','/services/v3/gaiaMobile/car/getPrivateNumber')
.set('scheme','https')
.set('timestamp',time)
.set('x-perm-id',ReqData.xPermId)
.set('x-broker-token',ReqData.token)
.set('referer', 'https://mp-merchant.fleetingpower.com/')
.send(phoneData)
.end((err,response)=>{
  console.log('getPhone response',JSON.parse(response.text))
  var data = JSON.parse(response.text)
  if(data.code!=200){
    resolve(data);
  }else{
    resolve(data);//页面内容
  }
  return data
})
})
}


function loginGetData(plate){
   return login()
    .then((cookie)=>getData(cookie, plate))
    .then((response)=>getPhone(response))
    // .then((resonse, res)=>{
    //   return resonse.text
    // },(err)=>{
    //   return err
    // })
}



 
let login = ()=>{//先登陆
    var info = {mobile: "17381912715", password: "kd17381912715", verCode: "", platformType: 2, type: 2, openId: ""};
    var login_url = 'https://mecs.fleetingpower.com/services/v1/broker/login'
return new Promise((resolve,reject)=>{
superagent
.post(login_url)
.set('Content-Type','application/json;charset=UTF-8')
.set('origin','https://mp-merchant.fleetingpower.com')
.set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36')
.set('x-app-key','broker_portal')
.set('sign','83bcb2963ecb6b3fc602089f08eba9e2')
.set('authority','mecs.fleetingpower.com')
.set('path','/services/v1/broker/login')
.set('scheme','https')
.set('x-perm-id','06A2FA521E644BBCB5640C0FE24785D1')
.send(info)
.end((err,response)=>{
err && reject(err);
var cookie = JSON.stringify(response.header['set-cookie']).trim().split(';')[0].substring(2);

var res= {}
var userinfo = JSON.parse(response.text)
console.log('login data',response.headers)
res = {...userinfo.result, cookie: cookie, xPermId: response.headers['x-perm-id']}
  fs.writeFile('./files/token.txt', res.token,'utf8', function(err){
    console.log('err', err)
  })
  fs.writeFile('./files/xPermId.txt', res.xPermId,'utf8', function(err){
    console.log('err1', err)
  })
// console.log('cookie',res)
resolve(res);
// console.log('response.text', JSON.parse(response.text));//接口返回信息,是否登录成功！
})
})
}


// sign
const paramSort = res => {
    var str = []
    // 将对象转成数组
    for (var i in res) {
      str.push([i, res[i]])
    }
    // 对数组进行排序
    _sort(str, function (a, b) {
      return a[0] > b[0]
    })
    return str
  }
const signGenerate = res => {
    var objs = paramSort(res)
    var strs = ''
    for (let i = 0; i < objs.length; i++) {
      strs +=
        objs[i][0] +
        '' +
        (objs[i][1] === null || objs[i][1] === undefined ? '' : objs[i][1])
    }
    const _appSecret = '0d0950bafe126cf1659b64f31968dbb0'
    strs = MD5(_appSecret + strs + _appSecret).toLowerCase()
    return strs
  }

  /**
 * 模拟 sort 排序 (解决 Safari 下 sort 的 BUG)
 * @param  {Array}   array 需要排序的数组
 * @param  {Function} fn   排序函数
 * @return {Array}         返回排序后的数组
 */
const _sort = (array, fn) => {
    for (var i = 0; i < array.length - 1; i++) {
      var isSorted = true
      for (var j = 0; j < array.length - 1 - i; j++) {
        if (fn(array[j], array[j + 1]) > 0) {
          var temp = array[j]
          array[j] = array[j + 1]
          array[j + 1] = temp
          isSorted = false
        }
      }
      if (isSorted) {
        return false
      }
    }
  }

  function MD5(s) {
    //注意参数需要为string类型，否则会报错
     return crypto.createHash('md5').update(String(s)).digest('hex');
}


module.exports = router